package com.swust.book_shop.controller;

import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.swust.book_shop.constant.JWTConstant;
import com.swust.book_shop.pojo.Result;
import com.swust.book_shop.pojo.ResultCodeEnum;
import com.swust.book_shop.pojo.UserInfo;
import com.swust.book_shop.pojo.vo.AuthVo;
import com.swust.book_shop.pojo.vo.LoginVo;
import com.swust.book_shop.service.UserInfoService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.LogFactory;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liushuai
 * @create 2022-05-05 15:29
 */
@RestController
@Slf4j
@RequestMapping("/user")
@CrossOrigin(allowedHeaders = "*")
public class UserController {
    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public Result register(@RequestBody UserInfo userInfo, HttpServletRequest httpServletRequest){
        log.info("{}请求接口",httpServletRequest.getRemoteUser());
        final String password = SecureUtil.md5().digestHex(userInfo.getPassword());
        userInfo.setPassword(password);
        try {
            userInfoService.save(userInfo);
        } catch (Exception e) {
            e.printStackTrace();

            return Result.build(201,"账号重复注册");
        }
        return Result.ok();
    }
    @ApiOperation("返回用户权限信息")
    @PostMapping("/auth")
    public  Result getAuth(@RequestHeader(JWTConstant.AUTH_HEADER) String token){
        JWT jwt = JWTUtil.parseToken(token);
        String account = (String) jwt.getPayload("account");
        UserInfo user = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("account", account));
        return Result.ok(user.getIsUpBook());
    }
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo,HttpServletRequest httpServletRequest){
        log.info("{}请求接口",httpServletRequest.getRemoteHost());
        final String password = SecureUtil.md5().digestHex(loginVo.getPassword());
        final UserInfo user = userInfoService.getOne(
                new QueryWrapper<UserInfo>().eq("account", loginVo.getAccount()).eq("password", password));
        if(user == null){
            return  Result.build(203,"登陆失败");
        }else {
            Map<String,Object> palLoadMap = new HashMap<>(3);
            palLoadMap.put("account",user.getAccount());
            String token = JWTUtil.createToken(palLoadMap, JWTConstant.SECERT.getBytes(StandardCharsets.UTF_8));
            Map<String,Object> userMap = new HashMap<>(2);
            userMap.put("name",user.getUsername());
            userMap.put("token",token);
            return Result.ok(userMap);
        }
    }

    @ApiOperation("实名认证接口")
    @PostMapping("/real_auth")
    public  Result doAuth(@RequestBody @Validated AuthVo authVo,
                          @RequestHeader(JWTConstant.AUTH_HEADER) String token){
        JWT jwt = JWTUtil.parseToken(token);
        String account = (String)jwt.getPayload("account");
        UserInfo user = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("account", account));
        authVo.setId(user.getId());
        boolean b = false;
        try {
            b = userInfoService.doAuth(authVo);
        } catch (Exception e) {
            log.warn(e.getMessage());
            return Result.build(204,e.getMessage());
        }
        if(b){
            return Result.ok();
        }else {
            return  Result.fail();
        }


    }

}
